# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import Qt, QTreeWidgetItem
import os
import subprocess


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.ApplicationModal)
        MainWindow.setEnabled(True)
        MainWindow.resize(800, 600)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(800, 600))
        MainWindow.setMaximumSize(QtCore.QSize(800, 600))
        MainWindow.setFocusPolicy(QtCore.Qt.TabFocus)
        MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Droid Sans")
        font.setBold(True)
        font.setWeight(75)
        self.centralwidget.setFont(font)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 100, 781, 451))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.servisler = QtWidgets.QGroupBox(self.verticalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.servisler.sizePolicy().hasHeightForWidth())
        self.servisler.setSizePolicy(sizePolicy)
        self.servisler.setObjectName("servisler")
        self.treeWidget = QtWidgets.QTreeWidget(self.servisler)
        self.treeWidget.setGeometry(QtCore.QRect(0, 20, 781, 431))
        self.treeWidget.setColumnCount(4)
        self.treeWidget.setObjectName("treeWidget")
        self.treeWidget.header().setDefaultSectionSize(120)
        self.verticalLayout.addWidget(self.servisler)
        self.horizontalLayoutWidget_5 = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget_5.setGeometry(QtCore.QRect(10, 10, 221, 31))
        self.horizontalLayoutWidget_5.setObjectName("horizontalLayoutWidget_5")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_5)
        self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label = QtWidgets.QLabel(self.horizontalLayoutWidget_5)
        self.label.setObjectName("label")
        self.horizontalLayout_5.addWidget(self.label)
        self.horizontalLayoutWidget_6 = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(470, 10, 321, 31))
        self.horizontalLayoutWidget_6.setObjectName("horizontalLayoutWidget_6")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_6)
        self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.pushButton_baslat = QtWidgets.QPushButton(self.horizontalLayoutWidget_6)
        self.pushButton_baslat.setEnabled(False)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../.designer/backup/start-button.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_baslat.setIcon(icon)
        self.pushButton_baslat.setObjectName("pushButton_baslat")
        self.horizontalLayout_6.addWidget(self.pushButton_baslat)
        self.pushButton_durdur = QtWidgets.QPushButton(self.horizontalLayoutWidget_6)
        self.pushButton_durdur.setEnabled(False)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("../.designer/backup/stop.jpeg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_durdur.setIcon(icon1)
        self.pushButton_durdur.setObjectName("pushButton_durdur")
        self.horizontalLayout_6.addWidget(self.pushButton_durdur)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        self.menuDosya = QtWidgets.QMenu(self.menubar)
        self.menuDosya.setObjectName("menuDosya")
        self.menuYard_m = QtWidgets.QMenu(self.menubar)
        self.menuYard_m.setObjectName("menuYard_m")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.action_cikis = QtWidgets.QAction(MainWindow)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("../.designer/PycharmProjects/Misem/simgeler/cikis.svg"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.action_cikis.setIcon(icon2)
        self.action_cikis.setShortcutContext(QtCore.Qt.ApplicationShortcut)
        self.action_cikis.setMenuRole(QtWidgets.QAction.QuitRole)
        self.action_cikis.setObjectName("action_cikis")
        self.actionHakk_nda = QtWidgets.QAction(MainWindow)
        self.actionHakk_nda.setMenuRole(QtWidgets.QAction.AboutRole)
        self.actionHakk_nda.setObjectName("actionHakk_nda")
        self.menuDosya.addAction(self.action_cikis)
        self.menuYard_m.addAction(self.actionHakk_nda)
        self.menubar.addAction(self.menuDosya.menuAction())
        self.menubar.addAction(self.menuYard_m.menuAction())

        self.retranslateUi(MainWindow)
        self.getServices()
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Milis Servis Merkezi - MİSEM"))
        self.servisler.setTitle(_translate("MainWindow", "Servisler"))
        self.treeWidget.headerItem().setText(0, _translate("MainWindow", "Servis Adı"))
        self.treeWidget.setColumnWidth(0, 120)
        self.treeWidget.headerItem().setText(1, _translate("MainWindow", "Başlat Seviyesi"))
        self.treeWidget.setColumnWidth(1, 110)
        self.treeWidget.headerItem().setText(2, _translate("MainWindow", "Anlık Durum"))
        self.treeWidget.setColumnWidth(2, 100)
        self.treeWidget.headerItem().setText(3, _translate("MainWindow", "Süreç No"))
        self.treeWidget.setColumnWidth(3, 75)
        self.treeWidget.headerItem().setText(4, _translate("MainWindow", "Servis Açıklaması"))
        self.treeWidget.setColumnWidth(4, 375)
        self.label.setText(_translate("MainWindow", "Servisi Başlat/Durdur"))
        self.pushButton_baslat.setText(_translate("MainWindow", "Başlat"))
        self.pushButton_durdur.setText(_translate("MainWindow", "Durdur"))
        self.menuDosya.setTitle(_translate("MainWindow", "Dosya"))
        self.menuYard_m.setTitle(_translate("MainWindow", "Yardım"))
        self.action_cikis.setText(_translate("MainWindow", "Çıkış"))
        self.actionHakk_nda.setText(_translate("MainWindow", "Hakkında"))

    def get_process_id(self,process):
        if process == "postgresql":
            process = "postgres"
        elif process == "nfs-server":
            process = "nfsd"
        elif process == "sysklogd":
            process = "syslogd"

        command = subprocess.run("pgrep %s | head -n 1" % process, shell=True, stdout=subprocess.PIPE, universal_newlines=True)
        output = command.stdout
        return output

    def get_service_desc(self,process):
        self.service_desc_list = {
            'alsa':'Gelişmiş Linux ses mimarisi',
            'cups':'CUPS yazdırma sistemi',
            'dbus':'Freedesktop mesaj otobüs sistemi',
            'gpm':'Sanal konsollar için fare sunucusu ve kes-yapıştır aracı',
            'lightdm':'Hafif bir giriş yöneticisi',
            'mysql':'MySQL ilişkisel veritabanı yönetim sistemi',
            'netfs':'NFS,SMB ve NCP dosya sistemleri için bağla-ayır için kullanılan bir başlangıç zamanı betiği',
            'network':'Ağ yönetim sistemi servisi',
            'nfs-server':'Ağ temelli paylaşımlı dosya sistemi',
            'plymouth':'Grafik önyükleme başlatma ekranı',
            'postgresql':'Gelişmiş nesne-ilişkisel veritabanı yönetim sistemi',
            'pppd':'Çevirmeli ağ yapılandırma servisi',
            'rpcbind':'Çeşitli protokoller üzerinden RPC\'yi destekleme',
            'rsyncd':'Dosyalardaki farklılıkları göndererek bir ağ üzerinden eşleme',
            'samba':'SMB dosya sunucusu ve AD etki alanı sunucusu',
            'slapd':'Basit dizin erişim protokolü (LDAP) araç seti',
            'sshd':'SSH bağlantı araçlarının ücretsiz sürümü',
            'sysklogd':'Çekirdek tarafından verilen sistem mesajlarının günlüğe kaydedilmesi',
            'winbindd':'NT sunucularından isimleri çözümlemek için isim servisi anahtar programcığı'
        }

        for key,value in self.service_desc_list.items():
            if process == key:
                return value

    def getServices(self):
        self.init = {}
        self.init_level2 = 2
        self.init_level3 = 3
        self.init_level4 = 4
        self.init_level5 = 5
        self.ignore_files = ['.','README','bluetooth','sudo','reboot','modules','rc','halt','init_single','localnet','random','sendsignals','setclock','template']

        for files_init in sorted(os.listdir("/etc/init.d")):
            if not files_init in self.ignore_files:
                self.init[files_init] = []

        self.init_len = len(self.init)

        for files_rc2 in sorted(os.listdir("/etc/rc.d/rc2.d/")):
            if not files_rc2.startswith('README'):
                if files_rc2[3:] in self.init:
                    self.init.setdefault(files_rc2.format()[3:],[0]).append(self.init_level2)

        for files_rc3 in sorted(os.listdir("/etc/rc.d/rc3.d/")):
            if not files_rc3.startswith('README'):
                if files_rc3[3:] in self.init:
                    self.init.setdefault(files_rc3.format()[3:],[1]).append(self.init_level3)

        for files_rc4 in sorted(os.listdir("/etc/rc.d/rc4.d/")):
            if not files_rc4.startswith('README'):
                if files_rc4[3:] in self.init:
                    self.init.setdefault(files_rc4.format()[3:],[2]).append(self.init_level4)

        for files_rc5 in sorted(os.listdir("/etc/rc.d/rc5.d/")):
            if not files_rc5.startswith('README'):
                if files_rc5[3:] in self.init:
                    self.init.setdefault(files_rc5.format()[3:],[3]).append(self.init_level5)

        for service in self.init:
            self.init.setdefault(service, [4]).append(self.get_process_id(service))

        for key,value in self.init.items():

                self.parent = self.treeWidget
                self.child = QTreeWidgetItem(self.parent)
                self.child.setFlags(self.child.flags() | Qt.ItemIsUserCheckable)
                self.child.setText(0, "{}".format(key))
                self.child.setCheckState(0, Qt.Unchecked)
                if value[0:4] == []:
                    self.child.setText(1, "-")
                elif value[0:4] == ['']:
                    self.child.setText(1, "{}".format("-").center(20))
                else:
                    self.child.setText(1, "{}".format(value[0:4]).center(20))

                if value[4:] == [] or value[4:] == ['']:
                    self.child.setText(2, "Çalışmıyor")
                    self.child.setForeground(2,QtGui.QBrush(QtGui.QColor("#ff0000")))
                else:
                    self.child.setText(2, "Çalışıyor")
                    self.child.setForeground(2, QtGui.QBrush(QtGui.QColor("#bff000")))

                if value[0:4] == "''":
                    self.child.setText(3, "-")
                else:
                    self.child.setText(3, "{}".format(value[4:]).replace('\'','').replace('[','').replace('[b','').replace(']','').replace('\\n','').center(10))
                self.child.setText(4, "{}".format(self.get_service_desc(key)))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
